<template>
	<div id="hello">
		<!-- 表头右键菜单 -->
		<div id="contextmenu">
			<el-button size="mini" type="primary" @click="addColumn()">插入列</el-button>
			<el-button type="primary" size="mini" @click="delColumn()">删除列</el-button>
			<el-button size="mini" type="primary" @click="addRow()">插入行</el-button>
			<el-button type="primary" @click="delRow" size="mini">删除行</el-button>


		</div>
		<!-- 表格 -->
		<el-table :data="testDatas" @selection-change="selectRow" ref="table" style="width: 100%;">
			<el-table-column type="selection" width="45"></el-table-column>
			<el-table-column v-for="(col, idx) in columnList" :key="col.prop" :index="idx">
				<!-- 自定义表头的内容 -->
				<template #header>
					<el-input size="mini" v-model="col.label">
					</el-input>
				</template>
				<!-- 自定义列的内容-->
				<template #default="scope">
					<el-input v-model="scope.row[col.prop].content">
					</el-input>
				</template>
			</el-table-column>
		</el-table>

	</div>
</template>

<script>
export default {
	data() {
		return {
			columnList: [
				{ prop: "name", label: '姓名', show: true },
			],
			testDatas: [
				{
					key: 0,
					name: { content: '张三', show: true },
				}, {
					key: 1,
					name: { content: '李四', show: true },
				}],
			count_col: 0,
			selectlistRow: []
		}
	},

	methods: {
		changeTestDatas() {
			this.testDatas.forEach((item, index) => {
				item.key = index
			})
		},
		// 获取表格选中时的数据
		selectRow(val) {
			// console.log(val);
			this.selectlistRow = []
			val.forEach(item => {
				this.selectlistRow.push(item.key)
			})

		},
		// 新增行
		addRow() {
			let obj = {}
			this.columnList.forEach(p => {
				obj[p.prop] = { content: '', show: true }
			})
			this.testDatas.push(obj)
			this.changeTestDatas()

		},
		// 删除行
		delRow() {
			this.testDatas = this.testDatas.filter(item => {
				let flag = this.selectlistRow.indexOf(item.key) == -1
				return flag
			})
			this.changeTestDatas()
			// 删除完数据之后清除勾选框
			this.$refs.table.clearSelection()
		},
		// 新增列
		addColumn() {
			var obj = { prop: 'col_' + this.count_col, label: '', show: true }
			this.columnList.push({ prop: 'col_' + this.count_col, label: '', show: true })
			this.testDatas.forEach(p => {
				this.$set(p, obj.prop, { content: '', show: true })
			})
			// console.log(this.columnList, this.testDatas);
			this.changeTestDatas()
			this.count_col++
		},
		// 删除列
		delColumn() {
			let colKey = this.columnList[this.columnList.length - 1].prop
			this.columnList.splice(this.columnList.length - 1, 1)
			this.testDatas.forEach(p => delete p[colKey])
			this.changeTestDatas()
		},
	}
}
</script>
  
<style lang="scss" scoped>
</style>